<?php
/**
 *title
 * @author: lican<364548233@qq.com>
 *Date: 2020/11/3
 *Time: 15:11
 */
namespace App\Http\Helpers;


use App\Http\Services\MsgService;
use App\Models\EmailCodeRecords;

class Mail{

    public static function send($users = ['364548233@qq.com', '49903151@qq.com'], $content = '', $attach = '')
    {
        $res =  \Illuminate\Support\Facades\Mail::send('emails.mail', ['content' => $content], function ($message) use ($users, $attach){
            $message->to($users)->subject('weixin商城');
            if($attach){
                $message->attach($attach,['as'=>'中文文档.xls']);
            }
        });
        // 返回的一个错误数组，利用此可以判断是否发送成功
        if(count(\Illuminate\Support\Facades\Mail::failures()) < 1){
            $expiredAt = now()->addMinutes(10);
            // 缓存验证码 10 分钟过期。
            if(is_array($users)){
                foreach($users as $user){
                    app('redis')->setex($user, 600, $content);
                }
            }else{
                app('redis')->setex($users, 600, $content);
            }
            self::emailCodeRecord($users, $content, json_encode($res), 0, '发送成功');
            return MsgService::getMsg(0, [
                'email' => $users,
                'expire_at' => $expiredAt->toDateTimeString()
            ]);
        }else{
            self::emailCodeRecord($users, $content, json_encode($res), 1, '发送失败');
            return MsgService::getMsg(-1);
        }
    }

    /**
     *记录邮件发送
     * @author lican<364548233@qq.com>
     */
    public static function emailCodeRecord($email, $code, $content = '', $status = 0, $remark = '发送成功'){
        $emailCodeRecords = new EmailCodeRecords();
        $emailCodeRecords->email = $email;
        $emailCodeRecords->code = $code;
        $emailCodeRecords->content = $content;
        $emailCodeRecords->status = $status;
        $emailCodeRecords->remark = $remark;
        $emailCodeRecords->save();
    }

}
